from jsonpath import jsonpath
from jsonpath_rw import Index, Fields
from jsonpath_rw_ext import parse

from common.logger import GetLogger


def update_value_to_json(json_object,json_path,new_value):
    json_path_expr = parse(json_path)
    #print(json_path_expr)
    for match in json_path_expr.find(json_object):
        #print(match)
        path = match.path
        #print(path)
        if isinstance(path,Index):
            match.context.value[match.path.index] = new_value
        elif isinstance(path,Fields):
            match.context.value[match.path.fields[0]]=new_value
    return json_object


def extract_json(json_object, json_path, index=0):
    res = jsonpath(json_object, json_path)
    GetLogger.logger.info(f'从{json_object}中通过【{json_path}】提取到的结果是：{res}')
    if res:
        # 如果index小于0，说明你要的是匹配到的全部结果，直接返回res
        if index < 0:
            return res
        else:
            return res[index]
    else:
        return res


if __name__ == '__main__':
    json_data={
        'goods_name':'商品名称',
        'price':300,
        'info':[
            {
                'aaa':'aaa',
                'bbb':'bbb'
            },
            {
                'aaa':'aaa1',
                'bbb':'bbb1'
            }
        ]
    }
    parmas = {
        '$.goods_name':'修改后的商品名称'
    }
    # # new_json_data = update_value_to_json(json_data,"$.goods_name","修改后的商品名称")
    # # # new_json_data = update_value_to_json(json_data, "$..aaa", "newaaa")
    # # new_json_data = update_value_to_json(json_data, "$.info[0].aaa", "newaaa")
    # print(new_json_data)
    for json_path,new_value in parmas.items():
        json_data=update_value_to_json(json_data,json_path,new_value)
    print(json_data)
    #数据提取
    #从json_data提取price
    res=jsonpath(json_data,"$.price")
    print(res)
    #提取所有aaa
    res = jsonpath(json_data, "$..aaa")
    print(res)
    #不存在的值返回False
    res = jsonpath(json_data, "$..aaa1")
    print(res)
    print(extract_json(json_data,"$.price"))
    print(extract_json(json_data, "$..aaa",index=1))
    print(extract_json(json_data, "$..aaa", index=-1))

